#13章 多线程
#_thread模块
#_thread.startnewthread简单示例
# import _thread
# from time import sleep
# from datetime import datetime
#
# datetime_format = '%y-%m-%d %H:%M:%S'
#
# def date_time_now(date_time):
#     return datetime.strftime(date_time,datetime_format)
#
# def loop_one():
#     print('线程1开始时间=',date_time_now((datetime.now())))
#     print('线程1休息4秒')
#     sleep(4)
#     print('线程1休息结束，结束时间=',date_time_now(datetime.now()))
#
# def loop_two():
#     print('线程2开始时间=',date_time_now((datetime.now())))
#     print('线程2休息2秒')
#     sleep(2)
#     print('线程2休息结束，结束时间=',date_time_now(datetime.now()))
#
# def main():
#     print('所有线程开始时间=',date_time_now(datetime.now()))
#     _thread.start_new_thread(loop_one,())
#     _thread.start_new_thread(loop_two,())
#     # 如果主线程不休眠，则会直接运行结束
#     # 当主线程休眠时，会在主线程休眠结束后退出所有线程
#     # 运行结束的时间会以主线程结束的时间为准
#     sleep(6)
#     print('所有线程结束时间=',date_time_now(datetime.now()))
#
# if __name__ == '__main__':
#     main()

#threading模块
#threading的thread类
print('------------threading的thread类----------------')
import threading
from time import sleep
from datetime import datetime

datetime_format = '%y-%m-%d %H:%M:%S'

loops = [4,2]
threads = []

def date_time_now(date_time):
    return datetime.strftime(date_time,datetime_format)

def loop_secs(name,secs):
    print('线程%s开始时间=%s'%(name,date_time_now((datetime.now()))))
    print('线程%s休息%s秒'%(name,secs))
    sleep(secs)
    print('线程%s休息结束，结束时间%s'%(name,date_time_now(datetime.now())))

def main():
    print('所有线程开始时间=',date_time_now(datetime.now()))
    _length = range(len(loops))
    for i in _length:
        t = threading.Thread(target=loop_secs,args=(i,loops[i]))
        threads.append(t)

    for i in _length:
        threads[i].start()

    for i in _length:
        threads[i].join()
    print('所有线程结束时间=',date_time_now(datetime.now()))

if __name__ == '__main__':
    main()